package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    WebSocketServer webSocketServer;

    /**
     * 提交订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //处理异常（收货地址为空，超出配送范围，购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //创建一个订单对象，将ordersSubmitDTO中的属性拷贝进去
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);

        //往对象中添加其他必要属性
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(0);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());

        //存入orders
        orderMapper.insert(orders);

        //创建订单明细对象
        List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        //存入订单明细集合
        orderDetailMapper.insertBatch(orderDetails);

        //根据userId删除购物车
        shoppingCartMapper.deleteByUserId(userId);

        //创建一个orderSubmitVO存储返回值
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        //orderSubmitVO
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        /*JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );*/

        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map map = new HashMap<>();
        map.put("type", 1);//1表示来单提醒
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 分页查看历史订单
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(Integer page, Integer pageSize, Integer status) {

        //设置分页条件
        PageHelper.startPage(page, pageSize);

        //创建一个Orders对象设置进userId和status
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setPage(page);
        ordersPageQueryDTO.setStatus(status);

        //进行分页查询返回一个Page<Orders>对象
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);

        //创建一个集合List<OrderVO>
        List<OrderVO> orderVOs = new ArrayList<>();
        List<Orders> ordersList = ordersPage.getResult();

        //遍历page中的list<Orders>集合
        if (ordersList != null && ordersList.size() != 0) {
            for (Orders orders : ordersList) {
                //创建一个OrderVO对象
                OrderVO orderVO = new OrderVO();

                //查询订单明细表
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orders.getId());

                //往orderVO存入数据
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                //将OrderVO对象存入OrderVOs
                orderVOs.add(orderVO);
            }
        }

        PageResult pageResult = new PageResult(ordersPage.getTotal(), orderVOs);
        return pageResult;
    }

    /**
     * 查看订单详情
     *
     * @param id
     * @return
     */
    public OrderVO details(Long id) {

        //根据id查询订单表获得一个订单对象orders
        Orders orders = orderMapper.getById(id);
        //根据orderId查询订单明细表获得一个OrderDetail对象
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        //根据orders和orderDetail创建一个OrderVO对象
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);

        //返回orderVO
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    public void userCancelById(Long id) {
        //根据id查询订单数据
        Orders order = orderMapper.getById(id);

        //订单不存在则抛出异常
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态为2待接单以上抛出异常
        if (order.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //订单状态为2，修改订单表支付状态
        Orders updateOrder = new Orders();
        updateOrder.setId(order.getId());
        if (Orders.TO_BE_CONFIRMED.equals(order.getStatus())) {
            updateOrder.setPayStatus(Orders.REFUND);
        }

        updateOrder.setStatus(Orders.CANCELLED);
        updateOrder.setCancelReason("用户取消");
        updateOrder.setCancelTime(LocalDateTime.now());
        orderMapper.update(updateOrder);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    public void repetition(Long id) {

        //根据orderId查询订单明细表
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //创建一个购物车集合
        List<ShoppingCart> shoppingCartList = new ArrayList<>();

        //遍历订单明细集合
        Long userId = BaseContext.getCurrentId();
        LocalDateTime now = LocalDateTime.now();
        if (orderDetailList != null && orderDetailList.size() != 0) {
            for (OrderDetail orderDetail : orderDetailList) {
                ShoppingCart shoppingCart = new ShoppingCart();

                //拷贝属性
                BeanUtils.copyProperties(orderDetail, shoppingCart);

                //设置userId和createTime
                shoppingCart.setUserId(userId);
                shoppingCart.setCreateTime(now);
                //加入购物车
                shoppingCartList.add(shoppingCart);
            }

            //批量插入购物车数据
            shoppingCartMapper.insertBatch(shoppingCartList);
        }
    }

    /**
     * 条件查询订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        //设置limit条件
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        //进行条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> ordersList = page.getResult();
        //将orderList转化为orderVOList
        List<OrderVO> orderVOList = getOrderVOList(ordersList);

        //返回结果
        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 将orderList转化为orderVOList
     *
     * @param ordersList
     * @return
     */
    private List<OrderVO> getOrderVOList(List<Orders> ordersList) {

        List<OrderVO> orderVOList = new ArrayList<>();

        //遍历订单集合
        if (ordersList != null && ordersList.size() != 0) {
            for (Orders orders : ordersList) {
                OrderVO orderVO = new OrderVO();

                //拷贝属性
                BeanUtils.copyProperties(orders, orderVO);

                //获得菜品字符串
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }

        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 订单状态数量统计
     *
     * @return
     */
    public OrderStatisticsVO statistics() {
        //查询Mapper层，获得三个订单状态数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        //封装结果
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        //返回
        return orderStatisticsVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //根据id查询对应订单数据
        Orders ordersFromDB = orderMapper.getById(ordersRejectionDTO.getId());

        //判断订单数据是否为待接单
        if (ordersFromDB == null || !Orders.TO_BE_CONFIRMED.equals(ordersFromDB.getStatus())) {
            //不是待接单，抛出异常
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //判断支付状态
        if (Orders.PAID.equals(ordersFromDB.getPayStatus())) {
            //已付款，执行退款操作
        }

        //修改订单状态和拒单理由
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //根据id查询订单数据
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //用户已支付
        if (Orders.PAID.equals(ordersDB.getPayStatus())) {
            //退款
        }

        //根据id修改订单状态、取消原因、取消时间
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    public void delivery(Long id) {
        //根据id查询订单数据
        Orders ordersDB = orderMapper.getById(id);

        //订单为空订单状态不是已接单
        if (ordersDB == null || !Orders.CONFIRMED.equals(ordersDB.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    public void complete(Long id) {
        //根据id查询订单数据
        Orders ordersDB = orderMapper.getById(id);

        //订单为空订单状态不是派送中
        if (ordersDB == null || !Orders.DELIVERY_IN_PROGRESS.equals(ordersDB.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     * @param id
     */
    public void reminder(Long id) {
        //查询这个订单
        Orders ordersDB = orderMapper.getById(id);

        //不存在该订单，抛出订单未找到异常
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //封装map集合
        Map map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + ordersDB.getNumber());
        //发送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }
}
